<template>
    <div class="header">
        <div class="header-left">
            <img src="@/assets/logo.png" alt="logo" class="logo">
            <span class="system-name">APIHub</span>
        </div>
        <div class="header-right">
            <!-- 主题选择下拉菜单 -->
            <div class="theme-selector" ref="themeSelectorRef">
                <button class="theme-toggle" @click="toggleThemeDropdown" :title="getThemeTitle()">
                    <i class="theme-icon">{{ getThemeIcon() }}</i>
                    <i class="dropdown-arrow" :class="{ 'rotate': showThemeDropdown }">▼</i>
                </button>

                <!-- 主题选择下拉框 -->
                <div class="theme-dropdown" v-if="showThemeDropdown" @click.stop>
                    <div class="theme-option" :class="{ 'active': currentTheme === 'light' }"
                        @click="selectTheme('light')">
                        <span class="theme-icon">☀️</span>
                        <span>经典亮色</span>
                    </div>
                    <div class="theme-option" :class="{ 'active': currentTheme === 'dark' }"
                        @click="selectTheme('dark')">
                        <span class="theme-icon">🌙</span>
                        <span>暗黑风格</span>
                    </div>
                    <div class="theme-option" :class="{ 'active': currentTheme === 'fresh' }"
                        @click="selectTheme('fresh')">
                        <span class="theme-icon">🌿</span>
                        <span>清新自然</span>
                    </div>
                    <div class="theme-option" :class="{ 'active': currentTheme === 'european' }"
                        @click="selectTheme('european')">
                        <span class="theme-icon">🎨</span>
                        <span>欧美风格</span>
                    </div>
                </div>
            </div>

            <div class="user-info" @click="toggleUserMenu" ref="userInfoRef">
                <img src="@/assets/user.webp" alt="user" class="user-avatar">
                <span class="user-name">{{ userStore.getUserInfo()?.nickname || '用户' }}</span>
                <i class="dropdown-icon flex-y-center" :class="{ 'rotate': showUserMenu }">
                    <iconExpand style="height: 14px; width: 14px;" class="icon-expand" />
                </i>

                <!-- 用户菜单下拉框 -->
                <div class="user-menu" v-if="showUserMenu" @click.stop>
                    <div class="menu-item" @click="handleUserSetting">
                        <IconProjectSetting class="icon-logout" />
                        <span>用户设置</span>
                    </div>
                    <div class="menu-item" @click="handleLogout">
                        <IconLogout class="icon-logout" />
                        <span>退出登录</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <el-dialog v-model="dialogFormVisible" title="修改信息" width="450">
        <el-form :model="form" label-width="auto" label-position="right" ref="formRef" label-suffix=":"
            class="pl-32px pr-32px">
            <el-form-item label="昵称">
                <el-input v-model="form.name" autocomplete="off" />
            </el-form-item>
            <el-form-item label="用户名">
                <el-input v-model="form.username" autocomplete="off" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="handleClose">取消</el-button>
                <el-button type="primary" @click="handleSubmit">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import { useTheme } from '@/composables/useTheme';
import { useUserStore } from "@/store/modules/user.ts";
import { updateUserInfo } from '@/common/apis/users/index.ts';
import { useEditorStore } from "@/store/modules/editStatus.ts";

const { currentTheme, setTheme } = useTheme();
const router = useRouter();
const userStore = useUserStore();
const dialogFormVisible = ref(false);
const formRef = ref(null);
const editorStore = useEditorStore();

// 用户菜单状态
const showUserMenu = ref(false);
const userInfoRef = ref<HTMLElement>();

// 主题选择状态
const showThemeDropdown = ref(false);
const themeSelectorRef = ref<HTMLElement>();

const form = reactive({
    name: '',
    username: ''
});

// 切换用户菜单显示状态
const toggleUserMenu = () => {
    showUserMenu.value = !showUserMenu.value;
};

// 切换主题下拉菜单
const toggleThemeDropdown = () => {
    showThemeDropdown.value = !showThemeDropdown.value;
};

// 选择主题
const selectTheme = (theme: 'light' | 'dark' | 'fresh' | 'european') => {
    setTheme(theme);
    showThemeDropdown.value = false;
};

// 获取主题图标
const getThemeIcon = () => {
    const icons = {
        light: '☀️',
        dark: '🌙',
        fresh: '🌿',
        european: '🎨'
    };
    return icons[currentTheme.value] || '☀️';
};

// 获取主题标题
const getThemeTitle = () => {
    const titles = {
        light: '经典亮色',
        dark: '暗黑风格',
        fresh: '清新自然',
        european: '欧美风格'
    };
    return titles[currentTheme.value] || '经典亮色';
};

// 处理未保存更改的确认
const confirmLoseChanges = async () => {
    if (!editorStore.hasUnsavedChanges) {
        return true;
    }

    try {
        await ElMessageBox.confirm(
            '您有未保存的更改，切换后将丢失，是否继续？',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        );
        editorStore.setHasUnsavedChanges(false);
        return true;
    } catch {
        return false;
    }
};

// 处理退出登录
const handleLogout = async () => {
    if (!await confirmLoseChanges()) return;
    userStore.logout();
    showUserMenu.value = false;
};

const handleClose = () => {
    formRef.value.resetFields();
    dialogFormVisible.value = false;
};

const handleSubmit = async () => {
    if (!form.name || !form.name.trim()) {
        ElMessage({
            message: '昵称不能为空',
            type: 'warning',
        });
        return;
    }
    const res = await updateUserInfo({ ...form });
    ElMessage.success({ message: `${res.message}，请重新登录` });
    handleClose();
    handleLogout();
};

// 处理用户设置
const handleUserSetting = () => {
    const { nickname, username } = userStore.userInfo;
    form.name = nickname || '';
    form.username = username || '';
    dialogFormVisible.value = true;
};

// 点击外部区域关闭菜单
const handleClickOutside = (event: Event) => {
    // 关闭用户菜单
    if (userInfoRef.value && !userInfoRef.value.contains(event.target as Node)) {
        showUserMenu.value = false;
    }

    // 关闭主题下拉菜单
    if (themeSelectorRef.value && !themeSelectorRef.value.contains(event.target as Node)) {
        showThemeDropdown.value = false;
    }
};

// 组件挂载时添加事件监听器
onMounted(() => {
    document.addEventListener('click', handleClickOutside);
});

// 组件卸载时移除事件监听器
onUnmounted(() => {
    document.removeEventListener('click', handleClickOutside);
});
</script>

<style lang="less" scoped>
// 使用CSS变量
.header {
    height: 64px;
    background: var(--header-bg);
    border-bottom: 1px solid var(--header-border);
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 24px;
    box-shadow: var(--shadow-light);
    position: sticky;
    top: 0;
    z-index: 100;
    transition: all 0.3s ease;
}

.header-left {
    display: flex;
    align-items: center;
    gap: 12px;
}

.logo {
    width: 48px;
    height: 48px;
    border-radius: 6px;
}

.system-name {
    font-size: 20px;
    font-weight: 600;
    color: var(--text-primary);
    letter-spacing: 0.5px;
    transition: color 0.3s ease;
}

.header-right {
    display: flex;
    align-items: center;
    gap: 20px;
}

// 主题选择器
.theme-selector {
    position: relative;
    display: inline-block;

    .theme-toggle {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 40px;
        height: 40px;
        background: var(--bg-primary);
        border: 1px solid var(--border-color);
        border-radius: 50%;
        cursor: pointer;
        transition: all 0.3s ease;
        font-size: 16px;
        color: var(--text-primary);
        position: relative;

        &:hover {
            background: var(--hover-bg);
            border-color: var(--primary-color);
            transform: scale(1.05);
            box-shadow: var(--shadow-medium);
        }

        &:active {
            transform: scale(0.95);
            box-shadow: var(--shadow-light);
        }

        .theme-icon {
            font-size: 18px;
            transition: transform 0.3s ease;
        }

        .dropdown-arrow {
            position: absolute;
            bottom: 2px;
            right: 2px;
            font-size: 8px;
            transition: transform 0.3s ease;
            color: var(--text-secondary);
            background: var(--bg-primary);
            border-radius: 50%;
            width: 12px;
            height: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            border: 1px solid var(--border-color);

            &.rotate {
                transform: rotate(180deg);
            }
        }
    }

    .theme-dropdown {
        position: absolute;
        top: 100%;
        right: 0;
        margin-top: 8px;
        min-width: 160px;
        background: var(--card-bg);
        border: 1px solid var(--border-color);
        border-radius: 8px;
        box-shadow: var(--shadow-medium);
        z-index: 1000;
        overflow: hidden;

        .theme-option {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 16px;
            cursor: pointer;
            transition: all 0.2s ease;
            color: var(--text-primary);
            border-bottom: 1px solid var(--border-light);

            &:last-child {
                border-bottom: none;
            }

            &:hover {
                background: var(--hover-bg);
            }

            &.active {
                background: var(--primary-color);
                color: var(--bg-primary);

                .theme-icon {
                    transform: scale(1.1);
                }
            }

            .theme-icon {
                font-size: 16px;
                transition: transform 0.2s ease;
            }

            span:last-child {
                font-size: 14px;
                font-weight: 500;
            }
        }
    }
}

.user-info {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 6px 12px;
    border-radius: 20px;
    cursor: pointer;
    transition: all 0.3s ease;

    &:hover {
        background: var(--bg-secondary);
    }

    .icon-expand {
        fill: var(--text-primary);
    }
}

.user-avatar {
    width: 28px;
    height: 28px;
    border-radius: 50%;
    object-fit: cover;
}

.user-name {
    font-size: 14px;
    color: var(--text-primary);
    font-weight: 500;
    transition: color 0.3s ease;
}

.dropdown-icon {
    color: var(--text-tertiary);
    margin-left: 4px;
    transition: transform 0.5s ease;

    &.rotate {
        transform: rotate(180deg);
    }
}

// 用户菜单样式
.user-menu {
    position: absolute;
    top: 100%;
    right: 0;
    margin-top: 8px;
    background: var(--bg-primary);
    border: 1px solid var(--border-color);
    border-radius: 8px;
    box-shadow: var(--shadow-medium);
    min-width: 140px;
    z-index: 1000;
    animation: slideDown 0.2s ease-out;

    &::before {
        content: '';
        position: absolute;
        top: -6px;
        right: 20px;
        width: 0;
        height: 0;
        border-left: 6px solid transparent;
        border-right: 6px solid transparent;
        border-bottom: 6px solid var(--bg-primary);
    }

    &::after {
        content: '';
        position: absolute;
        top: -7px;
        right: 20px;
        width: 0;
        height: 0;
        border-left: 6px solid transparent;
        border-right: 6px solid transparent;
        border-bottom: 6px solid var(--border-color);
    }
}

.menu-item {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 12px 16px;
    cursor: pointer;
    transition: all 0.2s ease;
    color: var(--text-primary);
    font-size: 14px;

    &:hover {
        background: var(--bg-secondary);
        color: var(--primary-color);
    }

    &:first-child {
        border-radius: 8px 8px 0 0;
    }

    &:last-child {
        border-radius: 0 0 8px 8px;
    }

    .icon-logout {
        fill: var(--text-primary);
    }
}

// 下拉动画
@keyframes slideDown {
    from {
        opacity: 0;
        transform: translateY(-10px);
    }

    to {
        opacity: 1;
        transform: translateY(0);
    }
}
</style>